package com.lcf.app.generator.common;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcf.common.web.PageDTO;
import com.lcf.common.web.Result;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;

/**
 * @param <M> mapper
 * @param <T> po
 */
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T, VO> extends ServiceImpl<M, T> {

    @Autowired
    protected M mapper;

    /**
     * POJO转为PO
     *
     * @return
     */
    public <POJO> T toEntity(POJO dto, Class<T> clazz) {
        return BeanUtil.copyProperties(dto, clazz);
    }

    public Result<VO> getInfo(Serializable id) {
        return Result.success((VO) super.getById(id));
    }

    public <DTO> Result<T> saveInfo(DTO dto) {
        T t = BeanUtil.copyProperties(dto, getEntityClass());
        return this.save(t) ? Result.success(t) : Result.fail("添加失败！");
    }

    public <DTO> Result<T> updateInfo(DTO dto) {
        T t = BeanUtil.copyProperties(dto, getEntityClass());
        return this.updateById(t) ? Result.success(t) : Result.fail("修改失败！");
    }

    public Result<String> removeInfo(Serializable id) {
        return this.removeById(id) ? Result.success() : Result.fail("删除失败！");
    }

    public Result<Page<VO>> paging(PageDTO dto) {
        return Result.success(mapper.paging(new Page(dto.getPageNum(), dto.getPageSize()), dto));
    }

}
